package service.Imp;

import Message.*;
import Message.vo.PageBeanVO;
import Message.Prompt.MessageConstant;
import Message.Prompt.PasswordConstant;
import Message.Prompt.StatusConstant;
import Message.entity.Employee;
import Message.DTO.UpdatePasswordDTO;
import lombok.extern.slf4j.Slf4j;
import mapper.EmployeeMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import service.EmployeeService;
import javax.security.auth.login.AccountNotFoundException;
import java.util.List;


@Slf4j
@Service
public class EmployeeServiceImp implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMopper;


    @Override
    public Employee login(Employee employee) throws Exception {

      String username = employee.getUsername();
       String passWord = employee.getPassword();


        //1、根据用户名查询数据库中的数据
        log.info("正在查询用户名：{}", username);
        Employee employees = employeeMopper.login(username);
        log.info("查询结果：{}", employees);

        //
        if(employees==null){
            log.error("用户不存在：{}", username);
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);

        }if(employees.getStatus().equals(StatusConstant.DISABLE)){

            throw new AccountNotFoundException(MessageConstant.ACCOUNT_LOCKED);
        }
        //密码比对
        //需要进行md5加密，然后再进行比对
        passWord = DigestUtils.md5DigestAsHex(passWord.getBytes());

        if (!passWord.equals(employees.getPassword())) {
            //密码错误
            throw new Exception(MessageConstant.PASSWORD_ERROR);
        }
        log.info("密码相同：{}", passWord);
        log.info("密码相同：{}",employees.getPassword());

        return employees;

    }

    @Override
    public boolean addEmp(Employee emp) {

        Employee employee = new Employee();


        BeanUtils.copyProperties(emp, employee);

        // 1.补充缺失的属性值
        // 补充密码字段，需要进行MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(StatusConstant.ENABLE);

        // 若未提供身份证号(id_number)，为满足数据库非空约束，生成占位值
        if (employee.getId_number() == null || employee.getId_number().trim().isEmpty()) {
            // 简单占位：当前时间戳后8位，避免为空导致插入失败
            String placeholderIdNum = "ID" + (System.currentTimeMillis() % 100000000L);
            employee.setId_number(placeholderIdNum);
        }


         int affected = employeeMopper.insert(employee);
         return affected == 1;

    }

    @Override
    public Employee getEmpById(long id) {
        return employeeMopper.getById(id);
    }

    @Override
    public Object editPassword(UpdatePasswordDTO emp) throws Exception {

        Long id = emp.getEmpId();
        String oldPassWorld = emp.getOldPassword();
        String newPassWord = emp.getNewPassword();
        oldPassWorld = DigestUtils.md5DigestAsHex(oldPassWorld.getBytes());
        newPassWord = DigestUtils.md5DigestAsHex(newPassWord.getBytes());
        Employee employee = employeeMopper.getUpdateId(id);
        if(oldPassWorld.equals(employee.getPassword())){

            employeeMopper.setPassword(id, newPassWord);

        }else {

            throw new Exception(MessageConstant.PASSWORD_ERROR);

        }

        return Result.success(employee);
    }

    @Override
    public Result SelectPage(PageBeanVO pageBean) {
        log.info("分页查询员工：{}", pageBean);
        
        // 获取查询参数
        String name = pageBean.getName();
        Integer page = pageBean.getPage();
        Integer pageSize = pageBean.getPageSize();
        
        // 处理分页参数
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        // 处理姓名参数，如果为空则查询所有
        if (name == null) {
            name = "";
        }
        // 计算偏移量
        Integer page1 = (page - 1) * pageSize;
        
        // 查询总数
        Long total = employeeMopper.getCount(name);
        
        // 查询分页数据
        List<Employee> records = employeeMopper.getPage(name, page1, pageSize);
        
        // 构建返回结果
        PageBeanVO result = new PageBeanVO();
        result.setName(name);
        result.setPage(page);
        result.setPageSize(pageSize);
        result.setTotal(total);
        result.setRecords(records);
        
        log.info("分页查询结果：总数={}, 当前页数据量={}", total, records.size());
        
        return Result.success(result);
    }

    @Override
    public void updateEmp(Employee employee) {
        int affected = employeeMopper.updateEmp(employee);
        if (affected == 1) {
            employeeMopper.getById(employee.getId());
        }
    }

    @Override
    public void updateEmpStatus(Integer status, long id) {

        employeeMopper.updateEmpStatus(status,id);


    }
}
